package com.zhaolang.qogir.ui.settings;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.utils.Log;
import com.zhaolang.qogir.R;
import com.zhaolang.qogir.ble.BasePrintActivity;
import com.zhaolang.qogir.ui.TitleView;
import com.zhaolang.qogir.ui.adapter.settings.SettingsBTAdapter;
import com.zhaolang.qogir.util.BluetoothUtil;
import com.zhaolang.qogir.util.PrintUtil;

import java.net.Socket;
import java.util.List;

public class ActivitySettingsBTPrinter extends BasePrintActivity implements View.OnClickListener {
    private TextView tvOpenBt, tvBtSearchStatus, btn_ble_disconnect;
    private ImageView ivBtStatus;
    private TextView tvBtHelp, tv_printer_select, btn_printer_test;
    private TitleView mTitle;
    private ListView lv_settings_bt_list;
    private LinearLayout layout_ble_connected;
    private SettingsBTAdapter settingsBTAdapter;
    final static int TASK_TYPE_CONNECT = 1;
    final static int TASK_TYPE_PRINT = 2;
    private int mSelectedPosition = -1;

    private final int BASE = 20;
    private final int MSG_CONNECT_BLE = BASE + 1;
    private final int MSG_RECONNECT_BLE = BASE + 2;
    private BluetoothSocket mSocket = null;

    private Handler mHander = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CONNECT_BLE:
                    BluetoothDevice device = (BluetoothDevice) msg.obj;
                    String devName = device.getName();
                    tvBtSearchStatus.setText(devName);
                    tvBtHelp.setVisibility(View.GONE);
                    tv_printer_select.setVisibility(View.GONE);
                    tvOpenBt.setVisibility(View.GONE);
                    lv_settings_bt_list.setVisibility(View.GONE);
                    layout_ble_connected.setVisibility(View.VISIBLE);
                    break;
                case MSG_RECONNECT_BLE:
                    tvBtHelp.setVisibility(View.VISIBLE);
                    tvOpenBt.setVisibility(View.VISIBLE);
                    tv_printer_select.setVisibility(View.VISIBLE);
                    lv_settings_bt_list.setVisibility(View.VISIBLE);
                    layout_ble_connected.setVisibility(View.GONE);
                    fillAdapter();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onConnected(BluetoothSocket socket, int taskType, boolean connectStatus) {
        this.mSocket = socket;
    }

    @Override
    public void onConnectedCallback(boolean connectStatus) {
        if (connectStatus) {
            BluetoothDevice device = settingsBTAdapter.getItem(mSelectedPosition);
            mHander.sendMessage(mHander.obtainMessage(MSG_CONNECT_BLE, device));
        } else {
            //TODO ble disconnected
            mHander.sendMessageDelayed(Message.obtain(mHander, MSG_RECONNECT_BLE), 2000);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_printer_add);
        initView();
    }

    private void initView() {
        View title = findViewById(R.id.vg_title);
        mTitle = new TitleView(this, title);
        mTitle.setCenterText(R.string.settings_printer_add, null);
        mTitle.setLeftIcon(R.drawable.btn_back, this);
        tvOpenBt = findViewById(R.id.tv_open_bt);
        ivBtStatus = findViewById(R.id.iv_bt_status);
        tvBtHelp = findViewById(R.id.tv_bt_help);
        tvBtSearchStatus = findViewById(R.id.tv_bt_search_status);
        lv_settings_bt_list = findViewById(R.id.lv_settings_bt_list);
        btn_ble_disconnect = findViewById(R.id.btn_ble_disconnect);
        layout_ble_connected = findViewById(R.id.layout_ble_connected);
        tv_printer_select = findViewById(R.id.tv_printer_select);
        btn_printer_test = findViewById(R.id.btn_printer_test);

        if (BluetoothUtil.getDeviceConnected().getConnectStatus()) {
            /* devices has connected */
            BluetoothDevice device = BluetoothUtil.getDeviceConnected().getBluetoothDevice();
            mHander.sendMessage(mHander.obtainMessage(MSG_CONNECT_BLE, device));
            layout_ble_connected.setVisibility(View.VISIBLE);
        } else {
            layout_ble_connected.setVisibility(View.GONE);
        }

        tvOpenBt.setOnClickListener(this);
        tvBtHelp.setOnClickListener(this);
        btn_ble_disconnect.setOnClickListener(this);
        btn_printer_test.setOnClickListener(this);

        lv_settings_bt_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedPosition = position;
                settingsBTAdapter.notifyDataSetChanged();
                BluetoothDevice device = settingsBTAdapter.getItem(mSelectedPosition);
                if (device != null)
                    connectDevice(TASK_TYPE_CONNECT);
            }
        });

        if (!checkBluetoothState()) {
            tvBtSearchStatus.setText(R.string.ui_settings_bt_closed);
            tvOpenBt.setText(R.string.ui_settings_bt_open);
            ivBtStatus.setBackground(getResources().getDrawable(R.drawable.printer_bluetooth_closed));
            tvBtHelp.setVisibility(View.GONE);
        } else {
            tvBtSearchStatus.setText(R.string.settings_printer_search);
            tvOpenBt.setText(R.string.settings_printer_research);
            ivBtStatus.setBackground(getResources().getDrawable(R.drawable.printer_bluetooth_icon));
            tvBtHelp.setVisibility(View.VISIBLE);
        }
        tvBtHelp.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvBtHelp.getPaint().setAntiAlias(true);
        settingsBTAdapter = new SettingsBTAdapter(this);
        lv_settings_bt_list.setAdapter(settingsBTAdapter);
    }

    /**
     * validate bt if open
     *
     * @return
     */
    public boolean checkBluetoothState() {
        if (BluetoothUtil.isBluetoothOn()) {
            return true;
        } else {
            return false;
        }
    }

    private void openSetting() {
        BluetoothUtil.openBluetooth(this);
    }

    /**
     * 从所有已配对设备中找出打印设备并显示
     */
    private void fillAdapter() {
        //推荐使用 BluetoothUtil.getPairedPrinterDevices()
        List<BluetoothDevice> printerDevices = BluetoothUtil.getPairedDevices();
        settingsBTAdapter.clear();
        settingsBTAdapter.addAll(printerDevices);
        if (checkBluetoothState()) {
            tvBtSearchStatus.setText(R.string.settings_printer_complete);
            tvOpenBt.setText(R.string.settings_printer_research);
            ivBtStatus.setBackground(getResources().getDrawable(R.drawable.printer_bluetooth_icon));
            tvBtHelp.setVisibility(View.VISIBLE);
        }
        settingsBTAdapter.notifyDataSetChanged();
    }

    /**
     * 测试打印小票
     */
    private void printerTest() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test_image);
        if (mSocket != null) {
            PrintUtil.printTest(mSocket, bitmap);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case TitleView.ID_LEFT:
                finish();
            case R.id.tv_open_bt:
                if (!checkBluetoothState()) {
                    openSetting();
                } else {
                    tvBtSearchStatus.setText(R.string.settings_printer_search);
                    mHander.sendMessageDelayed(Message.obtain(mHander, MSG_RECONNECT_BLE), 2000);
                }
                break;
            case R.id.tv_bt_help:
                break;
            case R.id.btn_ble_disconnect:
                disconnectDevice();
                break;
            case R.id.btn_printer_test:
                printerTest();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        fillAdapter();
    }

    private void connectDevice(int taskType) {
        if (mSelectedPosition >= 0) {
            BluetoothDevice device = settingsBTAdapter.getItem(mSelectedPosition);
            if (device != null)
                super.connectDevice(device, taskType);
        } else {
            Toast.makeText(this, "还未选择打印设备", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 断开蓝牙设备连接
     */
    public void disconnectDevice() {
        if (mSelectedPosition >= 0) {
            BluetoothDevice device = settingsBTAdapter.getItem(mSelectedPosition);
            if (device != null)
                super.disconnectDevice();
            settingsBTAdapter.clear();
        } else if (BluetoothUtil.getDeviceConnected().getConnectStatus()) {
            super.disconnectDevice();
            settingsBTAdapter.clear();
        } else {
            Toast.makeText(this, "还未选择打印设备", Toast.LENGTH_SHORT).show();
        }
    }
}
